#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 8888
#define MAX_BUFFER_SIZE 1024

int main() {
    // 1. 创建套接字
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("创建套接字失败");
        return -1;
    }

    // 2. 准备服务器地址结构体
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    memset(server_addr.sin_zero, 0, sizeof(server_addr.sin_zero));

    // 3. 绑定地址到套接字
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("绑定地址失败");
        close(server_socket);
        return -1;
    }

    // 4. 监听端口，设置最大等待连接数为5
    if (listen(server_socket, 5) == -1) {
        perror("监听端口失败");
        close(server_socket);
        return -1;
    }
    printf("服务器启动，正在监听端口 %d...\n", PORT);

    while (1) {
        // 5. 接受客户端连接
        struct sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr);
        int client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
        if (client_socket == -1) {
            perror("接受客户端连接失败");
            continue;
        }
        char client_ip[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &(client_addr.sin_addr), client_ip, INET_ADDRSTRLEN);
        printf("客户端 %s 已连接\n", client_ip);

        // 6. 接收客户端发送的数据
        char buffer[MAX_BUFFER_SIZE];
        ssize_t bytes_read = read(client_socket, buffer, MAX_BUFFER_SIZE - 1);
        if (bytes_read > 0) {
            buffer[bytes_read] = '\0';
            printf("从客户端接收到消息：%s\n", buffer);

            // 7. 向客户端发送响应消息
            char response[MAX_BUFFER_SIZE];
            snprintf(response, MAX_BUFFER_SIZE, "已收到你的消息：%s", buffer);
            ssize_t bytes_sent = write(client_socket, response, strlen(response));
            if (bytes_sent == -1) {
                perror("向客户端发送消息失败");
            }
        }
        // 8. 关闭与该客户端的连接
        close(client_socket);
    }

    // 9. 关闭服务器套接字（正常情况下不会执行到这里，因为前面是死循环）
    close(server_socket);
    return 0;
}